package com.china.produce.strategy.annotation;

import com.china.produce.annotation.Eviction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;


/**
 * 策略模式
 *
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2023/2/11
 */
@Component
@Slf4j
public class EvictionStrategyAnnotationFactory implements ApplicationContextAware, InitializingBean
{

    private ApplicationContext applicationContext;


    private static final Map<String, EvictionStrategy> evictionStrategyMap = new HashMap<>();


    /**
     * 根据key获取具体策略
     *
     * @param inputEviction
     * @return
     */
    public EvictionStrategy getEviction(String inputEviction)
    {

        return evictionStrategyMap.get(inputEviction);
    }


    @Override
    public void afterPropertiesSet() throws Exception
    {

        Map<String, Object> beansMap = applicationContext.getBeansWithAnnotation(Eviction.class);

        beansMap.values().forEach(bean -> {
            if (bean instanceof EvictionStrategy) {
                String value = bean.getClass().getAnnotation(Eviction.class).value();
                evictionStrategyMap.put(value, (EvictionStrategy) bean);
            }
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {

        this.applicationContext = applicationContext;
    }
}
